package ATM.dao.impl;

import ATM.bean.RecordBean;
import ATM.dao.IRecordDAO;

import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class RecordDAOImpl extends BaseDAO implements IRecordDAO {
    @Override
    public void insert(RecordBean recordBean) {
        this.setConnection();
        try {
            ps = con.prepareStatement("insert into t_record (r_date,r_description,r_yue,r_username) values (?,?,?,?) ");
            ps.setObject(1, recordBean.getDate());
            ps.setObject(2, recordBean.getDescription());
            ps.setObject(3, recordBean.getYue());
            ps.setObject(4, recordBean.getUsername());
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            this.closeConnection();
        }
    }

    @Override
    public List<RecordBean> getRecordsByUsername(String username) {
        this.setConnection();
        List<RecordBean> list = new ArrayList<>();
        try {
            ps = con.prepareStatement("select *from t_record where r_username=?");
            ps.setObject(1, username);
            rs = ps.executeQuery();
            while (rs.next()) {
                RecordBean record = new RecordBean();
                record.setId(rs.getInt("pk_recordId"));
                record.setDate(LocalDate.parse(rs.getString("r_date")));
                record.setDescription(rs.getString("r_description"));
                record.setYue(rs.getInt("r_yue"));
                record.setUsername(rs.getString("r_username"));
                list.add(record);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            this.closeConnection();
        }

        return list;
    }
}
